package com.abvnet.project.water.project.controller;

import com.abvnet.common.utils.StringUtils;
import com.abvnet.common.utils.file.FileUploadUtils;
import com.abvnet.common.utils.file.FileUtils;
import com.abvnet.framework.aspectj.lang.annotation.Log;
import com.abvnet.framework.aspectj.lang.enums.BusinessType;
import com.abvnet.framework.config.AbvnetConfig;
import com.abvnet.framework.web.controller.BaseController;
import com.abvnet.framework.web.domain.AjaxResult;
import com.abvnet.framework.web.page.TableDataInfo;
import com.abvnet.project.system.config.domain.Config;
import com.abvnet.project.system.config.service.IConfigService;
import com.abvnet.project.water.project.domain.ProjectContract;
import com.abvnet.project.water.project.domain.ProjectInfo;
import com.abvnet.project.water.project.domain.ProjectStatus;
import com.abvnet.project.water.project.service.IProjectContractService;
import com.abvnet.project.water.project.service.IProjectInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 项目合同信息操作处理
 *
 * @author duj
 * @date 2019-08-15
 */
@Controller
@RequestMapping("/project/projectContract")
@Slf4j
public class ProjectContractController extends BaseController {
    private String prefix = "project/projectContract";

    @Autowired
    private IProjectContractService projectContractService;

    @Autowired
    private IProjectInfoService projectInfoService;

    @Autowired
    private IConfigService configService;

    @RequiresPermissions("project:projectContract:list")
    @GetMapping()
    public String projectContract() {
        return prefix + "/list";
    }

    /**
     * 查询项目合同列表
     */
    @RequiresPermissions("project:projectContract:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ProjectContract projectContract) {
        startPage();
        List<ProjectContract> list = projectContractService.selectProjectContractList(projectContract);
        return getDataTable(list);
    }

    /**
     * 新增项目合同
     */
    @GetMapping("/add/{projectId}")
    public String add(@PathVariable("projectId") Long projectId) {
        return prefix + "/add";
    }

    /**
     * 新增保存项目合同
     */
    @RequiresPermissions("project:projectContract:add")
    @Log(title = "项目合同", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(ProjectContract projectContract, @RequestParam("serviceFile") MultipartFile serviceFile,
                              @RequestParam("saleFile") MultipartFile saleFile) {
        try {
            if (serviceFile != null && !serviceFile.isEmpty()) {
                projectContract.setServiceContractName(serviceFile.getOriginalFilename());
                String serviceFileUrl = FileUploadUtils.upload(AbvnetConfig.getContractPath(), serviceFile);
                projectContract.setServiceContractUrl(serviceFileUrl);
            }
            if (saleFile != null && !saleFile.isEmpty()) {
                projectContract.setSaleContractName(saleFile.getOriginalFilename());
                String saleFileUrl = FileUploadUtils.upload(AbvnetConfig.getContractPath(), saleFile);
                projectContract.setSaleContractUrl(saleFileUrl);
            }
            ProjectInfo projectInfo = projectInfoService.selectProjectInfoById(projectContract.getProjectId());
            if (Integer.parseInt(projectInfo.getProgressCode()) < Integer.parseInt(ProjectStatus.CONTRACT.getCode())) {
                projectInfo.setProgressCode(ProjectStatus.CONTRACT.getCode());
                projectInfoService.updateProjectInfo(projectInfo);
            }
            return toAjax(projectContractService.insertProjectContract(projectContract));
        } catch (Exception e) {
            log.error("添加项目合同失败！", e);
            return error(e.getMessage());
        }
    }

    /**
     * 修改项目合同
     */
    @GetMapping("/edit/{contractId}")
    public String edit(@PathVariable("contractId") Long contractId, ModelMap mmap) {
        ProjectContract projectContract = projectContractService.selectProjectContractById(contractId);
        mmap.put("projectContract", projectContract);
        return prefix + "/edit";
    }

    /**
     * 修改保存项目合同
     */
    @RequiresPermissions("project:projectContract:edit")
    @Log(title = "项目合同", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ProjectContract projectContract) {
        return toAjax(projectContractService.updateProjectContract(projectContract));
    }

    /**
     * 删除项目合同
     */
    @RequiresPermissions("project:projectContract:remove")
    @Log(title = "项目合同", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(projectContractService.deleteProjectContractByIds(ids));
    }

    @GetMapping("/download")
    public void fileDownload(String fileName, HttpServletResponse response,
                             HttpServletRequest request) {
        try {
            String realFileName = StringUtils.substringAfterLast(fileName, "/");
            String filePath = AbvnetConfig.getContractPath() + fileName;
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, realFileName));
            FileUtils.writeBytes(filePath, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    @RequiresPermissions("project:projectContract:add")
    @Log(title = "合同模板", businessType = BusinessType.INSERT)
    @PostMapping("/upload")
    @ResponseBody
    public AjaxResult upload(@RequestParam("serviceFile") MultipartFile serviceFile,
                             @RequestParam(value = "saleFile", required = false) MultipartFile saleFile) {
        try {
            if (serviceFile != null && !serviceFile.isEmpty()) {
                Config config = configService.selectConfigByConfigKey("service.contract.tpl");
                if (config != null) {
                    String fileName = FileUploadUtils.upload(AbvnetConfig.getTplPath(),"service_contract_tpl",
                            serviceFile);
                    config.setConfigValue(fileName);
                    configService.updateConfig(config);
                }
            }
            if (saleFile != null && !saleFile.isEmpty()) {
                Config config = configService.selectConfigByConfigKey("sale.contract.tpl");
                if (config != null) {
                    String fileName = FileUploadUtils.upload(AbvnetConfig.getTplPath(),"sale_contract_tpl", saleFile);
                    config.setConfigValue(fileName);
                    configService.updateConfig(config);
                }
            }
            return AjaxResult.success();
        } catch (Exception e) {
            log.error("上传合同模板失败！", e);
            return error(e.getMessage());
        }
    }

    @GetMapping("/downloadTpl")
    public void downloadTpl(String key, HttpServletResponse response,
                             HttpServletRequest request) {
        try {
            Config config = configService.selectConfigByConfigKey(key);
            String filePath = AbvnetConfig.getTplPath() + config.getConfigValue();
            String ext = StringUtils.substringAfterLast(config.getConfigValue(), ".");
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, config.getConfigName()+"."+ext));
            FileUtils.writeBytes(filePath, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载模板失败", e);
        }
    }
}
